//
//  HHPlaceholderTextView.m
//  ifensi
//
//  Created by 贺瑞 on 16/9/9.
//  Copyright © 2016年 ifensi. All rights reserved.
//

#import "HHPlaceholderTextView.h"
#import <objc/runtime.h>

@implementation HHPlaceholderTextView

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:self];
    
}

- (void)awakeFromNib{
    [super awakeFromNib];
    [self commonInit];
}

- (instancetype)initWithFrame:(CGRect)frame{
    NSTextStorage* textStorage = [[NSTextStorage alloc] init];
    NSLayoutManager* layoutManager = [NSLayoutManager new];
    [textStorage addLayoutManager:layoutManager];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(frame.size.width, frame.size.height)];
    textContainer.widthTracksTextView = YES;
    textContainer.heightTracksTextView = YES;
    [layoutManager addTextContainer:textContainer];

    
    if(self = [super initWithFrame:frame]){
        [self commonInit];
    }
    return self;
}

- (void)commonInit{
    _placeholderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.6];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setNeedsDisplay)
                                                 name:UITextViewTextDidChangeNotification object:self];
    self.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
}




-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    
    if(_placeholder.length && !self.text.length ){
        
        NSMutableDictionary *attribute = [NSMutableDictionary dictionary];
        [attribute setValue:_placeholderColor   forKey:NSForegroundColorAttributeName];
        [attribute setValue:self.font   forKey:NSFontAttributeName];

        
        CGFloat insetLeft = self.textContainerInset.left + 3.5;
        CGFloat insetTop = self.textContainerInset.top;
        

        
        CGSize sizeText = [_placeholder boundingRectWithSize:CGRectInset(rect, insetLeft, insetTop).size
                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                  attributes:attribute
                                                     context:nil].size;
        CGRect drawRect = CGRectMake(insetLeft, insetTop, sizeText.width, sizeText.height);
        drawRect.size.height = CGFLOAT_MAX;
        [_placeholder drawInRect:drawRect withAttributes:attribute];
    }
    
}


@end
